package app.remote.common;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.derby.jdbc.EmbeddedDriver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.feed.RssChannelHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.sql.DataSource;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: haibo.wang
 * Date: 13-7-9
 * Time: 下午2:09
 * To change this template use File | Settings | File Templates.
 */
@Configuration
@ComponentScan("app.remote")
@EnableWebMvc
@EnableScheduling
public class AppConfig extends WebMvcConfigurerAdapter {

    @Bean
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(EmbeddedDriver.class.getName());
        dataSource.setUrl("jdbc:derby:rss;create=true");
        return dataSource;
    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
        //jdbcTemplate.execute("drop table rss_url");
        //jdbcTemplate.execute("create table rss_url(id int not null PRIMARY KEY GENERATED" +
        //        " ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),name varchar(100),url varchar(255),location varchar(100))");
        return jdbcTemplate;
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate restTemplate = new RestTemplate();
        RssChannelHttpMessageConverter rssChannelConverter = new RssChannelHttpMessageConverter();
        rssChannelConverter.setSupportedMediaTypes(Collections.singletonList(MediaType.TEXT_XML));
        restTemplate.getMessageConverters().add(rssChannelConverter);
        MappingJackson2HttpMessageConverter jackson2Converter = new MappingJackson2HttpMessageConverter();
        restTemplate.getMessageConverters().add(jackson2Converter);
        return restTemplate;
    }

    /*@Bean
    public HttpHeaders httpHeaders() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Authorization", String.format("Basic %s", Base64.getEncoder().encode("transmission:5679484".getBytes())));
        RestTemplate restTemplate = restTemplate();
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(httpHeaders);
        restTemplate.setErrorHandler(new ResponseErrorHandler() {
            @Override
            public boolean hasError(ClientHttpResponse response) throws IOException {
                if (response.getStatusCode() == HttpStatus.CONFLICT) {
                    String sessionId = response.getHeaders().getFirst("X-Transmission-Session-Id");
                    httpHeaders.add("X-Transmission-Session-Id", sessionId);
                    return false;
                }
                return true;
            }
            @Override
            public void handleError(ClientHttpResponse response) throws IOException {
            }
        });
        restTemplate.put("http:192.168.1.200:9091/transmission/rpc", requestEntity);
        return httpHeaders;
    }*/

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new ByteArrayHttpMessageConverter());
        StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
        stringConverter.setWriteAcceptCharset(false);
        ArrayList<MediaType> textTypes = new ArrayList<MediaType>();
        textTypes.add(MediaType.TEXT_PLAIN);
        textTypes.add(MediaType.TEXT_HTML);
        textTypes.add(MediaType.TEXT_XML);
        textTypes.add(MediaType.APPLICATION_XML);
        stringConverter.setSupportedMediaTypes(textTypes);
        converters.add(stringConverter);
        converters.add(new MappingJackson2HttpMessageConverter());
    }
}
